package com.xiaouyudeguang.common.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.xiaouyudeguang.common.reader.XMindReader;

import java.io.File;

public class XMindUtils {

    public static ArrayNode parse(String filePath, String... paths) {
        return parse(new File(filePath), paths);
    }

    public static ArrayNode parse(File file, String... paths) {
        JsonNode jsonNode = JsonObject.readTree(XMindReader.readXMind(file));
        return findByPath(jsonNode.withArray("children"), 0, paths);
    }

    private static ArrayNode findByPath(ArrayNode rootNode, int index, String... paths) {
        for (JsonNode jsonNode : rootNode) {
            if (jsonNode.path("content").asText().equals(paths[index])) {
                if (paths.length < index + 1) {
                    return null;
                }
                if (paths.length == index + 1) {
                    return jsonNode.withArray("children");
                }
                return findByPath(jsonNode.withArray("children"), index + 1, paths);
            }
        }
        return null;
    }
}